import 'dart:async';
import 'dart:isolate';
import 'package:easy_isolate/easy_isolate.dart';
import 'package:flutter/services.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'printer_service_platform_interface.dart';

typedef SocketDataHandler = void Function(String response);

void mainHandler(dynamic data, SendPort isolateSendPort) {

}

class PrinterService {

  final worker = Worker();

  PrinterService._privateConstructor();

  static final PrinterService _instance = PrinterService._privateConstructor();

  factory PrinterService(){
    return _instance;
  }

  Future<void> init(IsolateMessageHandler handler) async{
    await worker.init(mainHandler, handler, queueMode: true);
  }

  Future<String?> getPlatformVersion() {
    return PrinterServicePlatform.instance.getPlatformVersion();
  }

  void connect(String token, SocketDataHandler handler) {
    final wsUrl = Uri.parse('wss://oapi.jarvisgo.cn/ws/im/$token');
    var channel = WebSocketChannel.connect(wsUrl);

    channel.stream.listen((response) {
      handler(response);
    });
  }

  Future<void> addPrintTask(String data) async{
    RootIsolateToken token = RootIsolateToken.instance!;
    worker.sendMessage(PrintEvent(token, data));
  }

  void dispose() {
    worker.dispose();
  }
}

class PrintEvent{

  PrintEvent(this.token, this.data);

  final RootIsolateToken token;

  final String data;

}
